import { photo } from '../models'
import multer from 'multer'
import uuid from 'node-uuid'
import { Router } from 'express'
let routes = Router()
var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'src/static/photo')
  },
  filename: function (req, file, cb) {
    let id = uuid.v4()
    photo.upsert({
      id: id,
      order_id: req.body.id,
      type: file.originalname.substring(file.originalname.lastIndexOf('.'))
    })

    cb(null, id + '-' + req.body.id + file.originalname.substring(file.originalname.lastIndexOf('.')))
  }
})

let upload = multer({ storage: storage })
routes.post('/', upload.array('files', 12), (req, res) => {
  let orderId = req.params.orderId || uuid.v4()
  let photoId = uuid.v4()
  res.json({
    orderId: orderId,
    photoId: photoId
  })
})
routes.get('/order/:id', (req, res) => {
  photo.findAll({
    raw: true,
    where: {
      order_id: req.params.id
    }
  }).then(data => {
    let result = []
    data.forEach(item => {
      result.push(`http://127.0.0.1:8080/static/photo/${item.id}-${item.order_id}${item.type}`)
    })
    res.json(result)
  })
})
export default routes
